use winapi::ctypes::c_char;
use winapi::um::libloaderapi::LoadLibraryA;
use std::env;
use std::ffi::CString;
use std::path::PathBuf;
use tch::Cuda;
///因为tch库0.20这个版本有问题 没有加载torch_cuda.dll,导致无法使用gpu,所以在运行时手动加载该动态链接库
///这个解决方案是从github tch仓库的issue处获取的<br>
///https://github.com/LaurentMazare/tch-rs/issues/907#issuecomment-2518111644
pub fn enable_cuda() {
    // 1. 获取环境变量
    let libtorch_path =
        env::var("LIBTORCH").unwrap_or_else(|_| panic!("LIBTORCH environment variable not set"));

    let mut lib_path = PathBuf::from(libtorch_path);
    lib_path.push("lib");
    lib_path.push("torch_cuda.dll");

    assert!(
        lib_path.exists(),
        "LibTorch lib directory missing at {:?}",
        lib_path
    );

    // 4. 转换为 C 兼容字符串
    let c_path = CString::new(lib_path.to_str().unwrap()).expect("Path contains null bytes");

    unsafe {
        LoadLibraryA(c_path.as_ptr() as *const c_char);
    }
    assert_eq!(Cuda::is_available(),true);
}
